package com.jly.edu.controller;


import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jly.edu.common.dto.PassDto;
import com.jly.edu.common.lang.Const;
import com.jly.edu.common.lang.Result;
import com.jly.edu.entity.SysRole;
import com.jly.edu.entity.SysUser;
import com.jly.edu.entity.SysUserRole;
import com.jly.edu.service.SysCommonService;
import com.jly.edu.service.SysRoleService;
import com.jly.edu.service.SysUserRoleService;
import com.jly.edu.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 作者：纪联友
 * @since 2021-10-22
 */
@RestController
@RequestMapping("/sys-user")
public class SysUserController extends BaseController {


    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysCommonService sysCommonService;
    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    PasswordEncoder passwordEncoder;
    /**
     * 获取当前登录用户
     */
    @GetMapping("/info")
    public Result info(Principal principal) {
        String username = principal.getName();
        SysUser sysUser = sysUserService.getByUsername(username);
        return Result.success(sysUser);

    }

    @GetMapping("/info/{id}")
    @PreAuthorize("hasAuthority('sys:user:list')")
    public Result info(@PathVariable Long id) {
        SysUser user = sysUserService.getById(id);
        Assert.notNull(user, "找不到该管理员！");
    List<SysRole> roles = sysRoleService.listRolesByUserId(user.getId());
    user.setSysRoles(roles);
    return Result.success(user);
    }
    /**
     * 获取role 分页
     * @param username
     * @return
     */
    @PreAuthorize("hasAnyAuthority('sys:user:list')")
    @GetMapping("/list")
    public Result getUserList(String username,String phone){

        Page<SysUser> userPages= sysUserService.page(getPage(), new QueryWrapper<SysUser>()
                .like(StrUtil.isNotBlank(username), "username", username)
                .like(StrUtil.isNotBlank(phone),"phone",phone));
        userPages.getRecords().forEach(u -> {
            u.setSysRoles(sysRoleService.listRolesByUserId(u.getId()));
        });
        return Result.success(userPages);
    }

    /**
     *  超级管理员重置密码
     */
    @PostMapping("/repass")
    @PreAuthorize("hasAuthority('sys:user:repass')")
    public Result repass(@RequestBody Long userId) {
        SysUser sysUser = sysUserService.getById(userId);
        if(sysUser == null){
            return Result.fail("当前用户不存在");
        }
        sysUser.setPassword(passwordEncoder.encode(Const.DEFAULT_PASSWORD));
        sysUser.setUpdateTime(LocalDateTime.now());
        sysUserService.updateById(sysUser);
        return Result.success(null);
    }
    /**
     * 用户自己修改密码
     *
     */
    @PostMapping("/updatePass")
    public Result updatePass(@Validated @RequestBody PassDto passDto, Principal principal) {
        SysUser sysUser = sysUserService.getByUsername(principal.getName());
        boolean matches = passwordEncoder.matches(passDto.getCurrentPass(), sysUser.getPassword());
        if (!matches) {
            return Result.fail("旧密码不正确！");
        }
        sysUser.setPassword(passwordEncoder.encode(passDto.getPassword()));
        sysUser.setUpdateTime(LocalDateTime.now());
        sysUserService.updateById(sysUser);
        return Result.success(null);
    }
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('sys:user:save')")
    public Result save(@Validated @RequestBody SysUser sysUser) {

        if(sysUserService.getByUsername(sysUser.getUsername()) != null)
        {
            return Result.fail("用户名已经存在");
        }
        sysUser.setCreateTime(LocalDateTime.now());
        sysUser.setStatus(Const.STATUS_ON);

        // 默认密码
        String password = passwordEncoder.encode(Const.DEFAULT_PASSWORD);
        sysUser.setPassword(password);

        // 默认头像
        sysUser.setAvatar(Const.DEFAULT_AVATAR);

        sysUserService.save(sysUser);
        return Result.success(sysUser);
    }

    @PostMapping("/update")
    @PreAuthorize("hasAuthority('sys:user:update')")
    public Result update(@Validated @RequestBody SysUser sysUser) {

        sysUser.setUpdateTime(LocalDateTime.now());
        sysUserService.updateById(sysUser);

        return Result.success(sysUser);
    }


    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('sys:user:delete')")
    public Result delete(@RequestBody Long[] ids){
        // 缓存同步删除
        Arrays.stream(ids).forEach(id -> {
            // 更新缓存
            SysUser sysUser = sysUserService.getById(id);
            sysCommonService.clearUserAuthorityInfo(sysUser.getUsername());
        });
        sysUserService.removeByIds(Arrays.asList(ids));
        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().in("user_id", ids));

        return Result.success("");
    }


    @Transactional
    @PostMapping("/role/{userId}")
    @PreAuthorize("hasAuthority('sys:user:role')")
    public Result rolePerm(@PathVariable("userId") Long userId, @RequestBody Long[] roleIds) {

        List<SysUserRole> userRoles = new ArrayList<>();

        Arrays.stream(roleIds).forEach(r -> {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(r);
            sysUserRole.setUserId(userId);

            userRoles.add(sysUserRole);
        });

        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().eq("user_id", userId));
        sysUserRoleService.saveBatch(userRoles);

        // 删除缓存
        SysUser sysUser = sysUserService.getById(userId);
        sysCommonService.clearUserAuthorityInfo(sysUser.getUsername());

        return Result.success("");
    }
}
